#ifndef __HTTP_CONNECTION_H__
#define __HTTP_CONNECTION_H__

#include <cstdint>
#include <memory>
#include <unordered_map>
#include <string>
#include <boost/beast/http.hpp>
#include <boost/beast.hpp>
#include <boost/asio.hpp>

const uint32_t HTTP_TIMEOUT_SECONDS = 30; // HTTP请求超时时间
const uint32_t BUFFER_SIZE = 8192; // HTTP请求缓冲区大小

//处理 Http 请求
class HttpConnection : public std::enable_shared_from_this<HttpConnection>
{
public:
    using tcp = boost::asio::ip::tcp;
    using IOContext = boost::asio::io_context;

    HttpConnection(IOContext& io_context);

    void Start();
    tcp::socket& GetSocket() { return _socket; }

    boost::beast::http::request<boost::beast::http::dynamic_body>& GetRequest()  { return _request; }
    boost::beast::http::response<boost::beast::http::dynamic_body>& GetResponse()  { return _response;}
    std::unordered_map<std::string, std::string>& GetParams() { return _get_params; }
private:
    //检查请求是否超时
    void _CheckDeadline();
    //向客户端发送响应
    void _WriteResponse();
    //处理客户端请求
    void _HandleReq();
    //解析 GET 请求参数
    void _PreParseGetParam();

private:
    tcp::socket _socket;
    boost::beast::flat_buffer _buffer{BUFFER_SIZE}; //缓冲区
    boost::beast::http::request<boost::beast::http::dynamic_body> _request;   //请求
    boost::beast::http::response<boost::beast::http::dynamic_body> _response; //响应
    boost::asio::steady_timer _deadline{   //定时器
        _socket.get_executor(),
        std::chrono::seconds(HTTP_TIMEOUT_SECONDS)
    };
    std::string _get_url; //存储 GET 请求的 URL
    std::unordered_map<std::string, std::string> _get_params; //存储 GET 请求的参数
};



#endif // !__HTTP_CONNECTION_H__